const messager = {
  win: null,
  targetOrigin: '*',
  actions: {},
  init(win, targetOrigin, isListen = true) {
    return new Promise((res) => {
      messager.win = win;
      messager.targetOrigin = targetOrigin;
      messager.actions = {};
      isListen && window.addEventListener('message', messager.handleMessageListener, false);
      setTimeout(() => {
        res();
      });
    });
  },

  handleMessageListener: (event) => {
    if (!event.data || !event.data.type) {
      return;
    }
    const type = event.data.type;
    if (!messager.actions[type]) {
      return console.warn(`${type}: missing listener:游戏端`);
    }
    console.log(`messager: ${type}`, event.data.value);
    messager.actions[type](event.data.value);
  },

  on: (type, cb) => {
    if (!messager.actions[type]) {
      messager.actions[type] = cb;
    }
    return messager;
  },

  emit: (type, value) => {
    messager.win.postMessage(
      {
        type,
        value
      },
      messager.targetOrigin
    );
    return messager;
  },

  destroy() {
    window.removeEventListener('message', messager.handleMessageListener);
  }
};

export default messager;
